package com.koocloud.electroplatemanage.service.impl;
import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.CaseFormat;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.IncomePartJudgeFieldMapper;
import com.koocloud.electroplatemanage.pojo.DrawNoVo;
import com.koocloud.electroplatemanage.pojo.IncomePartJudgeFieldVo;
import com.koocloud.electroplatemanage.service.IncomePartJudgeFieldService;
import com.koocloud.electroplatemanage.utils.SecondCheck;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: electroplatemanage
 * @description: 来料接收与判定字段服务实现类
 * @author: zww
 * @create: 2020-10-10 11:23
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class IncomePartJudgeFieldServiceImpl implements IncomePartJudgeFieldService {
    @Resource
    private IncomePartJudgeFieldMapper incomePartJudgeFieldMapper;
    Lock lock=new ReentrantLock();
    /**
     *@Description:查询来料接收与判定表字段表启用字段信息查询的相关信息并驼峰(根据orderid排序)
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/14
     */
    @Override
    public ResponseTemplate selectEnableFieldInfoForVo() {
        try {
            //查询启用字段数
            int enableFieldCount = incomePartJudgeFieldMapper.selectCountEnableField();
            //查询来料接收与判定表字段表启用字段的相关信息
            List<IncomePartJudgeFieldVo> listIncomePartJudgeFieldVo = incomePartJudgeFieldMapper.selectEnableFieldInfo();
            if (listIncomePartJudgeFieldVo.size()>0) {
                for(IncomePartJudgeFieldVo incomePartJudgeFieldVo:listIncomePartJudgeFieldVo) {
                    incomePartJudgeFieldVo.setEnfieldName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, incomePartJudgeFieldVo.getEnfieldName()));
                }
                //查询到数据
                return ResponseTemplate.builder().code(0).message("启用字段信息查询成功").count((long)enableFieldCount).data(listIncomePartJudgeFieldVo).build();
            } else {
                //没有查询到数据
                return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
            }
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }

    /**
     *@Description:查询来料接收与判定表字段表启用字段的相关信息(根据orderid排序)
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/10
     */
    @Override
    public ResponseTemplate selectEnableFieldInfo(String page, String limit,String idOrName) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                //查询启用字段数
                int enableFieldCount = incomePartJudgeFieldMapper.selectCountEnableField();
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                //查询来料接收与判定表字段表启用字段的相关信息
                List<IncomePartJudgeFieldVo> listIncomePartJudgeFieldVo = incomePartJudgeFieldMapper.selectEnableFieldInfo();
                if (listIncomePartJudgeFieldVo.size()>0) {
                    for(IncomePartJudgeFieldVo incomePartJudgeFieldVo:listIncomePartJudgeFieldVo) {
                        incomePartJudgeFieldVo.setEnfieldName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, incomePartJudgeFieldVo.getEnfieldName()));
                    }
                    //构造分页实体
                    PageInfo<IncomePartJudgeFieldVo> info=new PageInfo<>(listIncomePartJudgeFieldVo);
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("启用字段信息查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
            } catch (Exception e) {
                //事务手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //遇到异常，返回异常原因
                e.printStackTrace();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }

    }

    /**
     *@Description:查询来料接收与判定表字段表启用字段数
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/10
     */
    @Override
    public ResponseTemplate selectCountEnableField() {
        try {
            //查询启用字段数
            int enableFieldCount = incomePartJudgeFieldMapper.selectCountEnableField();
            if (enableFieldCount>0) {
                //查询到数据
                return ResponseTemplate.builder().code(0).message("查询启用字段数成功").count(1l).data(enableFieldCount).build();
            } else {
                //没有查询到数据
                return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
            }
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }


    /**
     *@Description:查询数据库最大orderId
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/16
     */
    @Override
    public ResponseTemplate selectFieldMaxOrderId() {
        try {
            //查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            if (fieldMaxOrderId>0) {
                fieldMaxOrderId = fieldMaxOrderId + 1;
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询最大orderId成功").count(1l).data(fieldMaxOrderId).build();

            } else {
                //没有查询到数据
                return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
            }
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description:新增扩列数据
     *@Param: [incomePartJudgeFieldVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/16
     */
    @Override
    public ResponseTemplate insert(IncomePartJudgeFieldVo incomePartJudgeFieldVo) {
        try {
            lock.lock();
            int orderId = incomePartJudgeFieldVo.getOrderId();
            //查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            fieldMaxOrderId = fieldMaxOrderId + 1;
            if(orderId<=fieldMaxOrderId) {//如果当前id小于等于数据库当前最大id
                incomePartJudgeFieldMapper.updateOrderId(orderId);
            }

            //设置科目号
            String fieldCode = "F"+String.format("%03d",fieldMaxOrderId);
            incomePartJudgeFieldVo.setFieldCode(fieldCode);
            //设置字段英文名称
            int defNo = fieldMaxOrderId-46;
            String enFieldName = "def"+String.valueOf(defNo);
            incomePartJudgeFieldVo.setEnfieldName(enFieldName);
            int rows = incomePartJudgeFieldMapper.insert(incomePartJudgeFieldVo);

            if(rows > 0) {
                return ResponseTemplate.builder().code(0).message("新增成功").count(0l).build();
            }
            else {
                return ResponseTemplate.builder().code(1).message("新增失败").count(0l).build();
            }

        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }

    /**
     *@Description:逻辑删除一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/10
     */
    @Override
    public ResponseTemplate delete(String fieldCode,String enableFlag) {


            try {
                lock.lock();
                int rows = incomePartJudgeFieldMapper.delete(fieldCode,enableFlag);
                //判断删除操作是否成功
                if (rows > 0) {
                    //删除成功返回数据
                    return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
                }
                else {
                    //删除失败返回提示
                    return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
                }
            } catch (Exception e) {
                //事务手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //遇到异常，返回异常原因
                e.printStackTrace();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
            finally {
                lock.unlock();
            }
    }

    /**
     *@Description:修改一条记录
     *@Param: [incomePartJudgeFieldVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/16
     */
    @Override
    public ResponseTemplate update(IncomePartJudgeFieldVo incomePartJudgeFieldVo) {
        try {
            lock.lock();
            String fieldCode = incomePartJudgeFieldVo.getFieldCode();
            //incomePartJudgeFieldMapper.s
            int orderId = incomePartJudgeFieldVo.getOrderId();
            //查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            int rows = 0;
            if(orderId > 0 && orderId<=fieldMaxOrderId) {//如果当前id小于等于数据库当前最大id
                incomePartJudgeFieldMapper.updateOrderId(orderId);
                rows = incomePartJudgeFieldMapper.update(incomePartJudgeFieldVo);
            } else if(orderId == fieldMaxOrderId) {
                rows = incomePartJudgeFieldMapper.update(incomePartJudgeFieldVo);
            }else {
                return ResponseTemplate.builder().code(1).message("当前顺序号过大,可填写顺序号为 1 - "+(fieldMaxOrderId)).count(0l).build();
            }
            if(rows>0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，可能的传参问题(原则上不出现)
                return ResponseTemplate.builder().code(1).message("修改数据失败,请检查参数").count(0l).build();
            }
            //没有异常并且修改数据条数大于0
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }

    /**
     *@Description:校验能否进行扩列
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/16
     */
    @Override
    //校验能否进行扩列
    public ResponseTemplate checkExpansion() {
        try{
            //开始查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            //判断是否是正常范围
            if (fieldMaxOrderId>0&&fieldMaxOrderId<255) {
                return ResponseTemplate.builder().code(0).message("可以扩列").count(0l).build();
            }
            else{
                return ResponseTemplate.builder().code(1).message("已达到扩列上限").count(0l).build();
            }
        }
        catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description:校验orderId
     *@Param: [orderId]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/16
     */
    @Override
    public ResponseTemplate checkOrderId(int orderId) {
        try{
            //开始查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            //取可填最大Id
            int orderIdFlag = fieldMaxOrderId + 1;
            //最大Id小于等于255
            if(orderId<=orderIdFlag&&orderId<=255&&orderId>0) {
                return ResponseTemplate.builder().code(0).message("符合要求").count(0l).build();
            }
            else {
                return ResponseTemplate.builder().code(1).message("您的排序号给的太大了,再减减").count(0l).build();
            }

        }
        catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
    /**
     *@Description:校验formula
     *@Param: [formula]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/27
     */
    @Override
    public ResponseTemplate checkFormula(String formula) {
        try{
            SecondCheck.formulaCheck(formula);
            if(SecondCheck.formulaCheck(formula)) {
                return ResponseTemplate.builder().code(0).message("符合要求").count(0l).build();
            }
            else {
                return ResponseTemplate.builder().code(1).message("需要输入九位数，且公式仅支持F255及以下科目号运算,运算符一位(共+、-、*、/、=五种,其中=表示名称相加)").count(0l).build();
            }

        }
        catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
    /**
     *@Description:
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/2
     */
    @Override
    public ResponseTemplate selectNotAuthEnableFieldInfo() {
        try {
            //查询启用字段数
            int enableFieldCount = incomePartJudgeFieldMapper.selectCountEnableField();
            //查询来料接收与判定表字段表非权限启用字段的相关信息
            List<IncomePartJudgeFieldVo> listIncomePartJudgeFieldVo = incomePartJudgeFieldMapper.selectNotAuthEnableFieldInfo();
            if (listIncomePartJudgeFieldVo.size()>0) {
                for(IncomePartJudgeFieldVo incomePartJudgeFieldVo:listIncomePartJudgeFieldVo) {
                    incomePartJudgeFieldVo.setEnfieldName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, incomePartJudgeFieldVo.getEnfieldName()));
                }
                //查询到数据
                return ResponseTemplate.builder().code(0).message("启用字段信息查询成功").count((long)enableFieldCount).data(listIncomePartJudgeFieldVo).build();
            } else {
                //没有查询到数据
                return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
            }
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
    /**
     *@Description:查询默认科目号
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/09
     */
    @Override
    public ResponseTemplate selectProjectNo() {
        try {
            //查询数据库最大orderId
            int fieldMaxOrderId = incomePartJudgeFieldMapper.selectFieldMaxOrderId();
            fieldMaxOrderId = fieldMaxOrderId + 1;


            //设置科目号
            String fieldCode = "F"+String.format("%03d",fieldMaxOrderId);
            return ResponseTemplate.builder().code(0).message("查询成功").data(fieldCode).count(0l).build();
        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //遇到异常，返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
}